package com.xxx.websocket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoop;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;

/**
 * description
 *
 * @author zk
 * @since 2018/9/12
 */
public class ServerStart {
    public static void main(String[] args) throws InterruptedException {
        ServerBootstrap wsBootstrap = new ServerBootstrap();
        wsBootstrap.group(new NioEventLoopGroup(),new NioEventLoopGroup())
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        ch.pipeline().addLast("httpShack",new HttpServerCodec())
                                .addLast("aggregaator",new HttpObjectAggregator(1024 * 50))
                        .addLast("websocketServer",new WebSocketServerProtocolHandler("/ws"))
                        .addLast("textFrameHandler", new SimpleChannelInboundHandler<TextWebSocketFrame>() {
                            @Override
                            protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
                                System.out.println(msg.text());
                                ctx.channel().writeAndFlush(new TextWebSocketFrame("ok i think your message is : " + msg.text()));
                            }
                        })
                        .addLast("binaryFrameHandler", new SimpleChannelInboundHandler<BinaryWebSocketFrame>() {
                            @Override
                            protected void channelRead0(ChannelHandlerContext ctx, BinaryWebSocketFrame msg) throws Exception {
                                System.out.println(new String(ByteBufUtil.getBytes(msg.content()),"UTF-8"));
                            }
                        });
                    }
                });
        ChannelFuture channelFuture = wsBootstrap.bind(9900).sync();
        channelFuture.channel().closeFuture().sync();
    }
}
